package vaccine.appointment.system.inventory.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import vaccine.appointment.system.inventory.dataobject.Inventory;

/**
 * 库存数据访问层
 */
@Mapper
public interface InventoryMapper extends BaseMapper<Inventory> {

    /**
     * 使用悲观锁查询库存（FOR UPDATE）
     * @param vaccineId 疫苗ID
     * @param vaccinationSiteId 接种点ID
     * @return 库存记录
     */
    @Select("SELECT * FROM inventory WHERE vaccine_id = #{vaccineId} AND vaccination_site_id = #{vaccinationSiteId} AND del_flg = 0 FOR UPDATE")
    Inventory selectForUpdate(@Param("vaccineId") Integer vaccineId, @Param("vaccinationSiteId") Integer vaccinationSiteId);

    /**
     * 原子性扣减库存
     * @param id 库存ID
     * @param count 扣减数量
     * @return 影响行数
     */
    @Update("UPDATE inventory SET count = count - #{count} WHERE id = #{id} AND count >= #{count} AND del_flg = 0")
    int decreaseStock(@Param("id") Integer id, @Param("count") Integer count);

    /**
     * 原子性增加库存
     * @param id 库存ID
     * @param count 增加数量
     * @return 影响行数
     */
    @Update("UPDATE inventory SET count = count + #{count} WHERE id = #{id} AND del_flg = 0")
    int increaseStock(@Param("id") Integer id, @Param("count") Integer count);
}
